<template>
  <Card dis-hover :bordered="false">
    <Form class="ivu-mb-16">
      <Button
        type="primary"
        class="ivu-fr"
        @click="handleAdd"
        v-hasC="{
          name: 'v1-base-plan-work-update-plan-work',
          flag: 'v1/base/plan-work/update-plan-work',
        }"
        >新增</Button
      >
      <text class="ivu-mr-16">默认班次：{{ classes }}</text>
      <a
        @click="handleSchedule"
        v-hasC="{
          name: 'v1-base-plan-work-update-plan-work-default',
          flag: 'v1/base/plan-work/update-plan-work-default',
        }"
        >编辑</a
      >
    </Form>
    <Table
      :columns="columns"
      :data="list"
      :loading="loading"
      :border="true"
      v-hasC="{
        name: 'v1-base-plan-work-index',
        flag: 'v1/base/plan-work/index',
      }"
    >
      <template #workTime="{ row }">
        <Tag v-if="row.work_on_am"
          >上午:{{ row.work_on_am }}-{{ row.work_off_am }}</Tag
        >
        <Tag v-if="row.work_on_pm"
          >下午:{{ row.work_on_pm }}-{{ row.work_off_pm }}</Tag
        >
      </template>
      <template #status="{ row }">
        <Badge v-if="+row.status === 1" status="success" text="正常" />
        <Badge v-if="+row.status === 0" status="error" text="停用" />
      </template>
      <template #action="{ row }">
        <a
          @click="handleEdit(row)"
          v-hasC="{
            name: 'v1-base-plan-work-update-plan-work2',
            flag: 'v1/base/plan-work/update-plan-work',
          }"
          >编辑</a
        >
        <Divider
          type="vertical"
          v-hasC="{
            name: 'v1-base-plan-work-delete-plan-work',
            flag: 'v1/base/plan-work/delete-plan-work',
          }"
        ></Divider>
        <a
          @click="handleDelete(row)"
          class="delete"
          v-hasC="{
            name: 'v1-base-plan-work-delete-plan-work',
            flag: 'v1/base/plan-work/delete-plan-work',
          }"
          >删除</a
        >
      </template>
    </Table>
    <Modal
      :title="add ? '新增' : '编辑'"
      width="960"
      v-model="modal"
      :mask-closable="false"
      :draggable="true"
      @on-cancel="handleCancel"
    >
      <Form
        :label-width="118"
        ref="formValidate"
        :model="formData"
        :rules="rules"
      >
        <FormItem label="班次名称" prop="name">
          <Input
            placeholder="请输入班次名称"
            v-model="formData.name"
            maxlength="16"
          />
        </FormItem>
        
        <FormItem label="工作时间" prop="workTime">
          <TimePicker
            class="ivu-mr-16"
            v-model="formData.morningTime"
            format="HH:mm"
            placement="bottom-end"
            type="timerange"
            placeholder="上午工作时间"
          />
          <TimePicker
            format="HH:mm"
            placement="bottom-end"
            v-model="formData.afternoonTime"
            type="timerange"
            placeholder="下午工作时间"
          />
        </FormItem>
        <FormItem label="排序" prop="sort">
          <InputNumber :min="1" :precision="0" v-model="formData.sort" />
        </FormItem>
        <FormItem label="状态" prop="status">
          <Switch v-model="formData.status" />
        </FormItem>
        <!-- <FormItem label="默认班次">
                    <Switch v-model="formData.default" />
                </FormItem> -->
      </Form>
      <template #footer>
        <Button @click="handleCancel">取消</Button>
        <Button type="primary" @click="handleSave" :loading="modalLoading"
          >确定</Button
        >
      </template>
    </Modal>
    <Modal
      title="编辑默认班次"
      width="580"
      v-model="scheduleModal"
      :mask-closable="false"
      :draggable="true"
    >
      <Form ref="formschedule" :model="schedule" :rules="schedulerules">
        <FormItem prop="id">
          <Select
            filterable
            clearable
            v-model="schedule.id"
            placeholder="请选择班次"
          >
            <Option v-for="item in classList" :value="item.id">{{
              item.name
            }}</Option>
          </Select>
        </FormItem>
      </Form>
      <template #footer>
        <Button @click="scheduleCancel">取消</Button>
        <Button type="primary" @click="scheduleSave" :loading="scheduleLoading"
          >确定</Button
        >
      </template>
    </Modal>
  </Card>
</template>
<script>
import { planworkList, updatePlanWork, deletePlanwork, planworkDefault, updateplanworkDefault } from '@/api/set'
import dayjs from 'dayjs'
export default {
  name: 'modalName',
  data () {
    return {
      add: true,
      modal: false,
      scheduleModal: false,
      classes: '',
      formData: {
        name: '',
        morningTime: [],
        afternoonTime: [],
        sort: null,
        status: true,
        workTime:'',
        id: ''
      },      
      schedule: {
        id: ''
      },
      loading: false,
      rules: {
        name: [{ required: true, message: '请输入班次名称', trigger: 'bulr' }],
        workTime: [{ required: true, message: '请输入工作时间', trigger: 'bulr' }],
      },
      schedulerules: {
        id: [
          { required: true, message: '请选择班次', trigger: 'change' }
        ]
      },
      columns: [
        {
          title: '班次名称',
          key: 'name',
          width: 128
        },
        {
          title: '上班时间',
          slot: 'workTime',
          minWidth: 158
        },
        {
          title: '排序',
          key: 'sort',
          width: 118
        },
        {
          title: '状态',
          slot: 'status',
          width: 118,
          sortable: true
        },
        {
          title: '创建时间',
          key: 'created_at',
          width: 160
        },
        {
          title: '操作',
          slot: 'action',
          width: 118
        }
      ],
      list: [],
      modalLoading: false,
      scheduleLoading: false,
      classList: []
    }
  },
  mounted () {
    this.getData()
    this._planworkDefault()
  },
  methods: {
    getData () {
      this.classList = []
      this.loading = true
      planworkList().then(res => {
        this.list = res
        this.list.map(item => {
          if (+item.status === 1) {
            this.classList.push({ id: item.id, name: item.name })
          }
        })
      }).finally(() => {
        this.loading = false
      })
    },
    //获取默认班次
    _planworkDefault () {
      planworkDefault().then(res => {
        this.classes = res.name
        this.schedule.id=res.id+''
      })
    },
    scheduleCancel () {
      this.scheduleModal = false
      this.$refs.formschedule.resetFields()
    },
    scheduleSave () {
      this.$refs.formschedule.validate((valid) => {        
        if (valid) {
          this.scheduleLoading = true
          updateplanworkDefault({ id: this.schedule.id }).then(res => {
            this._planworkDefault()
            this.scheduleLoading = false
            this.scheduleCancel()
          }).catch(() => {
            this.scheduleLoading = false
          })
        }
      })
    },
    handleAdd () {
      this.add = true
      this.modal = true
    },
    handleEdit (row) {
      this.add = false
      this.formData = {
        name: row.name,
        morningTime: [row.work_on_am, row.work_off_am],
        afternoonTime: [row.work_on_pm, row.work_off_pm],
        sort: row.sort,
        status: +row.status === 1 ? true : false,
        id: row.id
      },
        this.modal = true
    },
    handleCancel () {
      this.modal = false
      this.formData.morningTime = []
      this.formData.afternoonTime = []
      this.$refs.formValidate.resetFields()
    },
    handleSave () {
      if(this.formData.morningTime[0]||this.formData.afternoonTime[0] ){
        this.formData.workTime='workTime'
      }else{
        this.formData.workTime=''
      }
      this.$refs.formValidate.validate((valid) => {
        if (valid) {
          this.modalLoading = true
          const params = {
            name: this.formData.name,
            work_on_am: this.formData.morningTime[0] ? this.formData.morningTime[0] : '',
            work_off_am: this.formData.morningTime[1] ? this.formData.morningTime[1] : '',
            work_on_pm: this.formData.afternoonTime[0] ? this.formData.afternoonTime[0] : '',
            work_off_pm: this.formData.afternoonTime[1] ? this.formData.afternoonTime[1] : '',
            sort: this.formData.sort,
            status: this.formData.status === true ? 1 : 0
          }
          if (this.add) {
            updatePlanWork(params).then(res => {
              this.$Message.success('新增成功')
              this.handleCancel()
              this.getData()
              this.modalLoading = false
            }).catch(() => {
              this.modalLoading = false
            })
          } else {
            updatePlanWork(Object.assign({}, params, { id: this.formData.id })).then(res => {
              this.$Message.success('编辑成功')
              this.handleCancel()
              this.getData()
              this.modalLoading = false
            }).catch(() => {
              this.modalLoading = false
            })
          }
        }
      })
    },
    handleDelete (row) {
      this.$Modal.confirm({
        title: '温馨提示',
        content: '确定删除此项?',
        onOk: () => {
          deletePlanwork({ id: row.id }).then(res => {
            this.$Message.success('删除成功！')
            this.getData()
          })

        }
      })
    },
    handleSchedule () {
      this.scheduleModal = true
    }
  },

}
</script>
<style lang='less' scoped>
.imageUpdate {
  display: flex;
}

.delete {
  color: rgb(226, 5, 5);
}
</style>
